package com.school.dao;

import java.sql.*;

//JdbcUtils是提供的一个对JDBC进行简单封装的工具类，使用它能够简化JDBC应用程序的开发
public class DBUtil {
	private static final String JDBC_URL = "jdbc:mysql://localhost:3306/myschool?useSSL=false";

	private static final String DRIVER = "com.mysql.jdbc.Driver";

	private static final String USER = "root";

	private static final String PASS = "zy940425";

	protected static Connection connection = null;
	protected static PreparedStatement pstmt = null;
	protected static ResultSet rs = null;

	// 加载并注册驱动程序
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	// 获得连接对象
	public static Connection getConnection() throws SQLException {
		try {
			connection = DriverManager.getConnection(JDBC_URL, USER, PASS);
			return connection;
		} catch (SQLException e) {
			throw new SQLException("数据库连接失败", e);
		}
	}

	// 释放资源
	public static void close() {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (pstmt != null) {
			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
